package com.cci.kangdao.service.impl;

import com.cci.kangdao.dao.DictionariesTDao;
import com.cci.kangdao.dao.XgjGetUserInfoDao;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.service.XGJManagerService;
import com.cci.kangdao.utilTool.HttpUtils;
import com.cci.kangdao.utilTool.JsonUtils;
import com.cci.kangdao.xgj.XGJBasicResponse;
import com.cci.kangdao.xgj.XGJUserInfo;
import com.cci.kangdao.xgj.XgjApiConst;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service("XGJManagerService")
public class XGJManagerServiceImpl implements XGJManagerService {


    @Value("${xgj.api.url}")
    private String xgjUrl;

    @Value("${engineService.wwid}")
    private String wwid;

    @Value("${engineService.token}")
    private String token;

    @Resource
    private XgjGetUserInfoDao xgjGetUserInfoMapper;
    @Resource
    private DictionariesTDao dictionariesTDao;

    @Override
    public XGJBasicResponse updateUserInfo(Long userId, XGJUserInfo req) {
        String xgjDictUrl = dictionariesTDao.getListByDTableNameAndDInt("xgjUrl","0");
        if(StringUtils.isNotBlank(xgjDictUrl)){
            xgjUrl = xgjDictUrl;
        }
        String url = String.format(xgjUrl + XgjApiConst.XGJ_URL_USER, userId);
        XGJBasicResponse response = doPut(url, JSONObject.fromObject(req).toString(), XGJBasicResponse.class);
        return response;
    }

    private <T> T doPut(String url, String jsonString, Class<T> responseType) {
        Header wwidHeader = new BasicHeader("wwid", wwid);
        Header tokenHeader = new BasicHeader("token", token);
        System.out.println("芯管家同步用户坐标信息： "+ url);
        String response = HttpUtils.putJson(url,jsonString, new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                if (response.getStatusLine().getStatusCode() == 200
                        || response.getStatusLine().getStatusCode() == 206) {
                    HttpEntity httpEntity = response.getEntity();
                    return EntityUtils.toString(httpEntity);
                } else {
                    System.out.println("芯管家同步用户信息失败："+ url+"： 返回结果"+response);
                    /*LogUtils.error(Log.ERROR_LOGGER, "芯管家-变更接口：" + url
                            + "；返回结果：" + response);*/
                }
                return null;
            }
        }, wwidHeader, tokenHeader);
        System.out.println("芯管家同步用户信息返回结果："+ response);
        //LogUtils.info(Log.INFO_LOGGER, "芯管家-变更接口，返回数据：" + response);
        if (StringUtils.isNotEmpty(response)) {
            return JsonUtils.toJavaObject(response, responseType);
        }
        return null;
    }

    /**
     * 修改芯管家用户对应的服务站坐标
     */
    public void updateXgjLocation(Map map){
        String serviceStationId = map.get("serviceStationId").toString();
        List<UserT> userTS = xgjGetUserInfoMapper.XgjGetUserInfo(serviceStationId);
        XGJUserInfo xgjUserInfo = null;
        for (UserT user:userTS) {
            xgjUserInfo = new XGJUserInfo();
            XGJUserInfo.AddUserInfoEntity addUserInfoEntity = new XGJUserInfo.AddUserInfoEntity();
            addUserInfoEntity.setLat(map.get("lat").toString());
            addUserInfoEntity.setLon(map.get("lon").toString());
            xgjUserInfo.setLocation(addUserInfoEntity);
            updateUserInfo(user.getId(),xgjUserInfo);
        }
    }

}
